<?php
/**
 * Created by PhpStorm.
 * User: huliren<huliren0516@163.com>
 * Date: 2017/9/4
 * Time: 9:34
 */
require('../../../common.inc.php');

define('SITE_AUTH', 'advertising-line-ad');
use lib\core\AdminAction;
use Common\PhotoImage;
use Common\ResourcePathManager;
use Common\Oss;
use Center\AdvertiseImg as Model;
use Act\LinkConfig;

class advertising extends AdminAction
{
    private $list_url = 'data/modules/share/advertising.php';

    public function doDefault()
    {
        $smarty = $this->app->page();

        //活动链接获取
        $info = LinkConfig::getList(['Id >'=>0])['data'];
        $link = [];
        foreach($info as $v){
            $link[$v['LinkUrl']] = $v['Name'];
        }

        $where = ['Id >=' => 0];

        $page = $_GET['page'] < 1 ? 1 : (int)$_GET['page'];
        $limit = 5;
        $offset = ($page - 1) * $limit;

        $data = Model::getList($where,$limit,$offset);
        $count = $data['count'];
        if($count > 0){
            $page_info['page'] = ceil($count / $limit);
            $page_info['count'] = $count;

            $pagination = $this->pagination($count, $limit, $page);
            $smarty->value('page_info', $page_info);
            $smarty->value('pagination', $pagination);
            $smarty->value('list',$data['data']);
            $smarty->value('link',$link);
        }
        $smarty->output('share/advertising_list.tpl');
    }

    public function doEdit()
    {
        $smarty = $this->app->page();
        $id = intval(trim($_GET['id']));

        //活动链接获取
        $info = LinkConfig::getList(['Id >'=>0])['data'];
        $link = [];
        foreach($info as $v){
            $link[$v['LinkUrl']] = $v['Name'];
        }

        if ($id < 0) {
            HDshowMsg('数据不存在！', ['type' => 'error', 'url' => $this->list_url]);
        }
        if (!empty($id)) {
            $data = Model::getInfoByIds($id);
            if (empty($data)) {
                HDshowMsg('数据不存在！', ['type' => 'error', 'url' => $this->list_url]);
            }
            $smarty->value('info', $data);
        }
        $smarty->value('link', $link);
        $smarty->output('share/advertising_edit.tpl');
    }

    public function doUpdata()
    {
        $id = (isset($_POST['id']) and $_POST['id'] !=='')?$_POST['id']:null;
        $url = trim($_POST['link']);
        $img = $_FILES['img'];
        $start_time = $_POST['start_time'];
        $end_time = $_POST['end_time'];
        //数据入库
        if($id !== null){
            $info = [
                'Url' => $url,
                'StartTime' => $start_time,
                'EndTime' => $end_time,
            ];
            if (isset($img['name']) && $img['error'] == 0 && $img['size'] > 0) {
                // 复制图片
                $imgUrlAddre = self::saveImageUrl($_FILES['img']['tmp_name']);
                $info = array_merge($info,['ImgUrl'=>$imgUrlAddre]);
            }
            $rel =  Model::update($id,$info);
        }else{
            if (isset($img['name']) && $img['error'] == 0 && $img['size'] > 0) {
                // 复制图片
                $imgUrlAddre = self::saveImageUrl($_FILES['img']['tmp_name']);
            } else {
                HDshowMsg('图片上传失败！', ['type' => 'error', 'url' => $this->list_url]);
            }
            $info = [
                'ImgUrl' => $imgUrlAddre,
                'Url' => $url,
                'StartTime' => $start_time,
                'EndTime' => $end_time,
            ];

            $rel = Model::add($info);
        }

        if ($rel) {
            HDshowMsg('保存成功', ['type' => 'success', 'url' => $this->list_url]);
        } else {
            HDshowMsg('操作失败', ['type' => 'error', 'url' => $this->list_url]);
        }

    }

    public function doDelete()
    {
        $id = $_GET['id'];
        $rel = Model::delete($id);
        if ($rel) {
            HDshowMsg('删除成功', ['type' => 'success', 'url' => $this->list_url]);
        } else {
            HDshowMsg('操作失败', ['type' => 'error']);
        }
    }

    /**
     * @param $filename
     * @return bool|string
     */
    private static function saveImageUrl($filename)
    {
        $path = PhotoImage::getImageHash();
        $imageType = PhotoImage::getImageType($filename);
        $md5 = substr(md5(__KEY__ . microtime() . ''), -5) . rand(100, 999);

        $savePath = ResourcePathManager::getAdvertisingSavePath() . "{$path['hash1']}/{$path['hash2']}/{$path['hash3']}_{$md5}.$imageType";
        $res = Oss::PutFile($savePath, $filename, loadconf('oss/oss')['bucket']);
        if (empty($res)) {
            debug_log("getActUrl failed,, {$filename}", JF_LOG_WARNING);

            return false;
        }

        return ResourcePathManager::getOssImageUrl() . $savePath;
    }

}

$app->run();